package crowdedroom.hop4droid;

import static java.text.MessageFormat.format;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * The Class Util.
 */
public class Util {
  /**
   * Gets the connection.
   * @return the connection
   * @throws IOException Signals that an I/O exception has occurred.
   */
  public static HttpURLConnection getConnection() throws IOException {
    final URL url = new URL(Settings.apiURL);
    final HttpURLConnection connection =
      (HttpURLConnection) url.openConnection();
    connection.setDoOutput(true);
    connection.setRequestProperty(
      "Content-Type",
      Settings.contentType);
    connection.setRequestProperty("Accept", Settings.acceptsTypes);
    connection.setRequestMethod(Settings.method);
    return connection;
  }
  /**
   * Serialize throwable.
   * @param throwable the throwable
   * @return the string
   */
  public static String serializeThrowable(final Throwable throwable) {
    final StringBuilder builder = new StringBuilder();
    builder.append("<?xml version=\"1.0\"?>");
    builder.append("<notice version=\"" + Settings.version + "\">");
    builder.append("<api-key>" + Settings.apiKey + "</api-key>");
    builder.append("<notifier>");
    builder.append("<name>" + Settings.clientName + "</name>");
    builder.append("<version>"
      + Settings.clientVersion
      + "</version>");
    builder.append("<url>" + Settings.clientUrl + "</url>");
    builder.append("</notifier>");
    builder.append("<error>");
    builder.append("<class>"
      + throwable.getClass().getName()
      + "</class>");
    builder.append("<message>"
      + throwable.getMessage()
      + "</message>");
    builder.append("<backtrace>");
    for (final StackTraceElement element : throwable.getStackTrace()) {
      builder.append(format(
        "<line method=\"{0}.{1}\" file=\"{2}\" number=\"{3}\"/>",
        element.getClassName(),
        element.getFileName(),
        element.getLineNumber(),
        element.getMethodName()));
    }
    builder.append("</backtrace>");
    builder.append("</error>");
    builder
      .append("<server-environment><project-root>/root</project-root><environment-name>env</environment-name></server-environment>");
    builder.append("</notice>");
    return builder.toString();
  }
}
